//--------------------------------------------------------------------------------
// This file is part of the Windows Workflow Foundation Sample Code
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation.  See these other
// materials for detailed information regarding Microsoft code samples.
// 
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//--------------------------------------------------------------------------------

using System;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;
using System.Text;
using System.ComponentModel;
using Microsoft.Samples.Workflow.UI.Design;

namespace Microsoft.Samples.Workflow.UI
{
    [Serializable]
    [TypeConverter(typeof(PermissionTypeConverter))]
    public class Permission
    {
        string id;
        string role;
        SecurityException exception = null;

        public Permission() { }

        public Permission(string id, string role)
        {
            this.id = id;
            this.role = role;
        }

        public string ID
        {
            get { return this.id; }
            set { this.id = value; }
        }

        public string Role
        {
            get { return this.role; }
            set { this.role = value; }
        }

        internal SecurityException Exception
        {
            get { return this.exception; }
        }

        internal bool CheckPermission()
        {
            this.exception = null;
            bool permissionSatisfied = true;
            if (!string.IsNullOrEmpty(this.id) || !string.IsNullOrEmpty(this.role))
            {
                PrincipalPermission permission = new PrincipalPermission(this.id, this.role);
                try
                {
                    permission.Demand();
                }
                catch (SecurityException e)
                {
                    this.exception = e;
                    permissionSatisfied = false;
                }
            }

            return permissionSatisfied;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            return sb.Append(this.id).Append(";").Append(this.role).ToString();
        }
    }
}
